<?php
/**
 * Created by PhpStorm.
 * User: Eric
 * Email: 13522679763@163.com
 * Date: 2018/3/5
 * Time: 20:00
 */

namespace app\api\controller;

use app\api\model\Channel;
use app\api\model\CourseArticle;
use app\api\model\UserSubscribe;
use think\Controller;
use think\Db;
use app\api\model\Config;
use app\api\model\Magazine;
use app\api\model\Balance;
use app\api\model\Ebook;
use app\api\model\EbookCode;
use app\api\model\UserEbook;
use think\db\Query;
use app\api\model\User as UserModel;
use think\exception\DbException;


/**
 * Class User
 * @package app\api\controller
 * 公众号关注模块
 */
class User extends Controller
{
    /**
     * 初始化
     */

    private $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\User();

        //临时注释
        $user_id = input('user_id');
//        $user_id='MDAwMDAwMDAwMIGHfWyzq4Nx';
        defined('UID') or define('UID', decode($user_id));
    }

    /**
     * 我的二维码
     */
    public function my_code()
    {
//        $url=config('server_url').'/pages/index/index?user_id='.UID;
        $url = 'is_ios=1';
        $mycode = qr_code($url);
        json_success($mycode);
    }


	/**
	 * VIP会员页面数据
	 */
	public function vip()
	{
	    $user_id=input('user_id');
	        if (!$user_id){
	            json_fail('获取用户ID失败');
            }
            $user_id=decode($user_id);
	        $user=new \app\api\model\User();
		//获取用户信息
		$info=$user->where('id',$user_id)->field('id,real_name,nickname,old_nickname,is_vip,avatar_url,vip_start_time,vip_end_time')->find();
        $info['nickname']=base64_decode($info['nickname']);
        $info['vip_start_time']=   $info['vip_start_time']?date('Y年m月d日',$info['vip_start_time']):'';
        $info['vip_end_time']=date('Y年m月d日',$info['vip_end_time']);
		//获取开通VIP 的金额
		$config=Config::getByKey('vip');


        $data['user'] = $info;
        $data['type'] = 5;
        $data['vip_price'] = (int)($config['value'] / 100);
        if (empty($data)) {
            json_success([]);
        }
        json_success($data);
    }

    /**
     * 我的个人中心
     */
    public function my()
    {
//         'nickname' => base64_encode($nickname), //昵称
        $user = $this->model->field('id,real_name,nickname,old_nickname,is_vip,avatar_url,vip_start_time,vip_end_time')->where('id', UID)->find();
        if ($user) {
            $user['nickname'] = base64_decode($user['nickname']);
            $user['vip_start_time'] = date('Y.m.d', $user['vip_start_time']);
            $user['vip_end_time'] = date('Y.m.d', $user['vip_end_time']);
        }
        if (!empty($user)) {
            json_success($user);
        }
        json_success([]);

    }

    /**
     * 返回我的订单列表
     */
    public function my_order_list()
    {
        $type = input('type', '');
        if (!empty($type)) {
            $data = $this->order_list($type);
        } else {
            $type = ['2', '3', '4'];
            $data = $this->order_list($type);
        }
        if (empty($data)) {
            json_success([]);
        }
        json_success($data);
    }

    /**
     * 订单列表
     * @param $type
     * @return mixed
     */
    public function order_list($type)
    {
        $data['list'] = $this->model->alias('u')
            ->field('o.id,o.sn,o.pid,o.type,o.title,o.pay_price,o.pay_time,o.picture,o.status')
            ->where('u.id', UID)
            ->join('order o', 'o.user_id=u.id', 'left')
            ->where('o.type', 'in', $type)
            ->where('o.status', 1)
            ->select();
        foreach ($data['list'] as $k => $v) {
            $v['pay_time'] = date('Y-m-d H:i', $v['pay_time']);

            if ($v['type'] == 2) {
                $data['list'][$k]['type_name'] = '杂志';
                $data['list'][$k]['stage'] = Magazine::where('id', $v['pid'])->value('stage');
            }
            if ($v['type'] == 3) {
                $data['list'][$k]['type_name'] = '小课';
            }
            if ($v['type'] == 4) {
                $data['list'][$k]['type_name'] = 'TalkShow';
            }
        }
        return $data;
    }

    /**
     * 我的订阅杂志列表
     */
    public function my_magazine()
    {
        $type = 2;
        $data = $this->model
            ->alias('a')
            ->field('c.id,b.type,b.pid,b.is_forever,b.status,c.title,c.picture,c.stage')
            ->where('a.id', UID)
            ->join('user_subscribe b', 'b.user_id=a.id', 'left')
            ->join('magazine c', 'c.id=b.pid', 'left')
            ->where('b.type', $type)
            ->select();

        if (empty($data)) {
            json_success([]);
        }
        json_success($data);

    }

    /**
     * 我的小课列表
     * @throws \think\Exception
     */
    public function my_course($is_video=0)
    {
        $data = UserSubscribe::alias('a')
            ->field('a.user_id,a.type,a.pid,a.create_time,a.status,a.is_forever,c.id,c.title,c.sub_title,c.picture,c.is_video,c.content,c.ctype')
            ->where('a.user_id', UID)
            ->where('a.type', 3)
            ->join('course c', 'c.id=a.pid')
            ->where('c.status', 1)
            ->where('c.is_video', $is_video)
            ->select();
        foreach ($data as $k => $v) {

            $course_article = CourseArticle::field('title')->where('course_id', $v['id'])->where('status', 'neq', 0)->order('create_time desc')->find();
            $data[$k]['courses_article_title'] = $course_article['title'];
        }
        if (empty($data)) {
            json_success([]);
        }
        json_success($data);
    }

    /**
     * 我的 Talkshow
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function my_talk_show()
    {
        $data = UserSubscribe::alias('a')
            ->field('a.user_id,a.type,a.pid,a.create_time,a.status,a.is_forever,t.id,t.title,t.sub_title,t.picture,t.duration,t.author,t.content')
            ->where('a.user_id', UID)
            ->where('a.type', 4)
            ->join('talkshow t', 't.id=a.pid', 'left')
            ->select();
        foreach ($data as $k => $v) {
            if ($v['duration'] >= 3600) {
                //求小时数
                $hour = (int)($v['duration'] / 3600);
                $s = $v['duration'] % 3600;
                $minute = (int)($s / 60);
                $s = $v['duration'] % 60;
                $s = $s % 60;
                $data[$k]['duration'] = $hour . ':' . $minute . ':' . $s;
            } else {
                $data[$k]['duration'] = date('i:s', $v['duration']);
            }

        }
        if (empty($data)) {
            json_success([]);
        }
        json_success($data);

    }

    /**
     * 我的收益记录
     */
    public function income_record()
    {       //total_receive_price


        $data['user'] = $this->model->field('id,total_profit_price,total_receive_price')->where('id', UID)->find();
        
        $data['user']['total_profit_price'] = $data['user']['total_profit_price'] / 100;  //处理金额格式 为元
        $data['user']['total_receive_price'] = $data['user']['total_receive_price'] / 100;
        //可提现金额
        $data['user']['withdraw'] = ($data['user']['total_profit_price'] - $data['user']['total_receive_price']);

        //我邀请的好友 所贡献的收益
        $data['friend'] = $this->model->alias('a')
            ->field('a.id,a.nickname,a.avatar_url,a.source_id,b.create_time,b.update_time,b.total_price')
            ->where('source_type', 2)
            ->where('source_id', UID)
            ->join('user_pull b', 'b.user_id=a.id')
            ->select();


        foreach ($data['friend'] as $k => $v) {
            $v['nickname'] = base64_decode($v['nickname']);
            $v['create_time'] = date('Y-m-d H:i', $v['create_time']);
            $v['update_time'] = date('Y-m-d H:i', $v['update_time']);
            $v['total_price'] = $v['total_price'] / 100;
        }


        if (empty($data)) {
            json_success([]);
        }
        json_success($data);

    }

    /**
     * 获取提现记录列表
     */
    public function get_balance_log()
    {
        $map = array(
            'type' => 2,
            'user_id' => UID
        );
        $user_question = Balance::where($map)->whereIn('is_arrival', [1, 2])->order('id desc')->select();
        if ($user_question) {
            foreach ($user_question as $question) {
                $question->price = formatAmount($question->price);
                $question->current_price = formatAmount($question->current_price);
                $question->time = date('Y.m.d H:i', $question->time);
            }

            json_success($user_question);
        } else {
            json_success([]);
        }
    }


    /**
     * 用户提现
     * @author jihaichuan
     */
    public function user_present_record()
    {
        // 获取用户需要提现的金额
        $price = Input('record_price', 0);
        $price = $price * 100;

        // 获取用户信息   // 初始化数据库模型
        $user_info = new UserModel();
        $user_balance = new Balance();
//        $user_info->startTrans();
        // 查询是否有没有到账的费用
        $count = $user_balance->where(array('type' => 2, 'user_id' => UID, 'is_arrival' => 2))->count();
        if ($count > 0) {
//            $user_info->rollback();
            json_fail('提现已成功，正在打款中...');
        }

        // 获取目前可以提现的总金额
        $current_price = $this->get_current_price(); //返回可提现的金额

        if ($current_price <= 0) {
            json_fail('您账号余额为0元，不能提现');
        }

        // 判断账户余额是否充足
        if ($current_price < $price) {
            json_fail('您账号余额不足！');
        }

        // 判断提现金额不能超过5元；
        if ($price > 500) {
            json_fail('单次提现金额不能超过5元！');
        }

        // 每天不能提现2次；
        $start_time = strtotime(date('Y-m-d', time()));
        $count = $user_balance
            ->where('type', 2)
            ->where('user_id', UID)
            ->where('is_arrival', 'neq', 3)
            ->where('time', '>', $start_time)->count('id');
        if ($count >= 2) {
            json_fail('每天提现不能超过2次！');
        }

        // 生成提现编号
        $sn = orderNum();

        // 写入数据
        $add_data = array(
            'type' => 2,
            'sn' => $sn,
            'user_id' => UID,
            'price' => $price,
            'current_price' => $current_price - $price,
            'is_arrival' => 2,
            'time' => time(),
            'arrival_reason' => '到账处理中',
        );
        $id = $user_balance->insertGetId($add_data);
        if ($id) {
            // 增加写入提现金额；
            try {
                // 增加提现金额
                $rows = $user_info->where('id', UID)->setInc('total_receive_price', $price);
                if ($rows) {
                    // 查询提现信息
                    $info = $this->enterprisePay(UID, $sn, $price);
//                    $info = array(
//                        'err_code' => 'AMOUNT_LIMIT',
//                        'err_code_des' => '测试内容'
//                    );
                    // 判断是否有错误信息
                    if (isset($info['err_code'])) {
                        if ($info['err_code'] == 'SENDNUM_LIMIT') {
                            // 回滚事务
                            $user_info->where('id', UID)->setDec('total_receive_price', $price);
                            $user_balance->where('id=' . $id)->update(array(
                                'is_arrival' => 3,
                                'arrival_reason' => '今日提现次数已达上限',
                            ));
                            json_fail('今日提现次数已达上限');
                        }
                        if ($info['err_code'] == 'AMOUNT_LIMIT') {
                            $user_info->where('id', UID)->setDec('total_receive_price', $price);
                            $user_balance->where('id=' . $id)->update(array(
                                'is_arrival' => 3,
                                'arrival_reason' => '提现金额不能少于1元'
                            ));
                            json_fail('提现金额不能少于1元 ');
                        }
                    }
                    if ($info['result_code'] == 'SUCCESS') {
                        $rows3 = $user_balance->where('id=' . $id)->update(array(
                            'is_arrival' => 1,
                            'arrival_reason' => '到账成功'
                        ));
                        json_success('提现成功，24小时后到账！');
                    } else {
                        // 回滚事务
                        $user_info->where('id', UID)->setDec('total_receive_price', $price);
                        $user_balance->where('id=' . $id)->update(array(
                            'is_arrival' => 3,
                            'arrival_reason' => $info['err_code_des']
                        ));
                        json_fail('提现失败：' . $info['err_code_des']);
                    }
                } else {
                    // 回滚事务
                    $user_info->where('id', UID)->setDec('total_receive_price', $price);
                    $user_balance->where('id=' . $id)->update(array(
                        'is_arrival' => 3,
                        'arrival_reason' => '累计用户提现金额失败'
                    ));
                    json_fail('系统繁忙，请稍后操作..');
                }
            } catch (\Exception $e) {
                $user_info->where('id', UID)->setDec('total_receive_price', $price);
                $user_balance->where('id=' . $id)->update(array(
                    'is_arrival' => 3,
                    'arrival_reason' => '新增操作失败'
                ));
                json_fail('系统繁忙，请稍后操作..');
            }
        } else {
            json_fail('系统繁忙，请稍后操作..');
        }
    }


    /**
     * 获取当前金额
     * @return mixed
     * @author jihaichuan
     */
    public function get_current_price()
    {

        $info = \app\api\model\User::where('id', UID)->find();
        if (!$info) {
            return 0;
        }

        // 获取用户已提现金额
        $user_balance = new Balance();
        // 获取总金额
        $total_price = $user_balance->where(array(
            'type' => 1,      //1收入总金额
            'user_id' => UID
        ))->sum('price');

        //提现金额
        $receive_price = $user_balance->where(array(
            'type' => 2,            //2 提现总金额
            'user_id' => UID
        ))->where('is_arrival', 'neq', 3)->sum('price');

        // 判断提现金额是否超过获得金额
        $price = $total_price - $receive_price;
        if ($price < 0) {
            return 0;
        }
        // 返回可提现金额
        return $price;
    }


    /**
     * 企业向个人付款
     * @param $user_id
     * @param $sn
     * @param $amount
     * @return mixed
     * @author jihaichuan
     */
    protected function enterprisePay($user_id, $sn, $amount)
    {
        // 获取openid
        $openid = Db('user')->where(array('id' => $user_id))->value('openid');
        $pay = Config('PAY_WEIXIN');
        $desc = '消费者调查测评奖励';
        $params = array(
            'partner_trade_no' => $sn,
            'openid' => $openid,
            'check_name' => 'NO_CHECK',
            'amount' => $amount, // 总计
            'desc' => $desc,
        );
        $result = $this->payToUser($params, $pay['key'], $pay['appid'], $pay['mchid']);
        return $result;
    }

    /**
     * 企业向个人付款
     * @param $params
     * @param $key
     * @param $appid
     * @param $mchid
     * @return mixed
     * @author jihaichuan
     */
    protected function payToUser($params, $key, $appid, $mchid)
    {
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        //检测必填参数
        if ($params["partner_trade_no"] == null) {   //
            exit("退款申请接口中，缺少必填参数partner_trade_no！" . "<br>");
        } elseif ($params["openid"] == null) {
            exit("退款申请接口中，缺少必填参数openid！" . "<br>");
        } elseif ($params["check_name"] == null) {             //NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名（未实名认证的用户会校验失败，无法转账）OPTION_CHECK：针对已实名认证的用户才校验真实姓名（未实名认证用户不校验，可以转账成功）
            exit("退款申请接口中，缺少必填参数check_name！" . "<br>");
        } elseif (($params["check_name"] == 'FORCE_CHECK' or $params["check_name"] == 'OPTION_CHECK') && ($params["re_user_name"] == null)) {  //收款用户真实姓名。
            exit("退款申请接口中，缺少必填参数re_user_name！" . "<br>");
        } elseif ($params["amount"] == null) {
            exit("退款申请接口中，缺少必填参数amount！" . "<br>");
        } elseif ($params["desc"] == null) {
            exit("退款申请接口中，缺少必填参数desc！" . "<br>");
        }
        $params["mch_appid"] = $appid;//公众账号ID
        $params["mchid"] = $mchid;//商户号
        $params["nonce_str"] = time();//随机字符串
        $params['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'] == '::1' ? '192.168.0.1' : $_SERVER['REMOTE_ADDR'];//获取IP
        $params["sign"] = $this->getSign($params, $key);//签名
        $xml = arrayToXml($params);
        $apicent_cert = dirname(dirname(dirname(dirname(__FILE__)))) . '/vendor/Wxpay/apiclient_cert.pem';
        $apiclient_key = dirname(dirname(dirname(dirname(__FILE__)))) . '/vendor/Wxpay/apiclient_key.pem';

//        $apicent_cert = dirname(dirname(dirname(dirname(__FILE__)))) . '/config/cert/apiclient_cert.pem';
//        $apiclient_key =dirname(dirname(dirname(dirname(__FILE__)))) . '/config/cert/apiclient_key.pem';
        return postXmlSSLCurl($xml, $url, false, $apicent_cert, $apiclient_key);
    }


    /**
     * 签名加密
     * @param $params
     * @param $key
     * @return mixed
     * @author jihaichuan
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }


    /**
     * 签名加密
     * @param $paraMap
     * @param bool $urlEncode
     * @return string
     * @author jihaichuan
     */
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }


    public function index()
    {
        if (isset($_GET['echostr'])) {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];

            $token = 'xdfwechat';
            $array = array($timestamp, $nonce, $token);
            sort($array);
            $tmpStr = implode('', $array);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                echo $_GET['echostr'];
            }
        } else {
            $xmlStr = file_get_contents('php://input');
            $info = $this->xmlToArray($xmlStr);

            if ($info['Event'] == 'subscribe') {
                //二维码的参数值
                if ($info['EventKey']) {

                    $activity = substr($info['EventKey'], 8); //活动ID
                    $array = explode(',', $activity);
                    $activity_id = $array['0'];
                    $channel_id = $array['1'];
                    if ($channel_id) {
                        $Channel = new Channel();

                        Db::table('cx_test')->insertGetId(array('content' => $channel_id));
                        Db::table('cx_channel')->where('id', $channel_id)->setInc('total_subscribe', 1);

                    }
                    //Db::table('cx_test')->insertGetId(array('content'=>$activity_id));
                    //关注成功，发送模板通知，通过二维码扫描关注
                    $Notice = new Notice();
                    $Notice->follow_notice($activity_id, $info['FromUserName']);
                    if (!$this->isUserInfo($info['FromUserName'])) {
                        $Notice->pullUserInfo($info['FromUserName']);
                    }
                }
            }
            //取消关注
            if ($info['Event'] == 'unsubscribe') {
                $User = new \app\api\model\User();

                $User::where('openid_web', $info['FromUserName'])->update(array('is_subscribe_wechat' => 2, 'subscribe_time' => ''));
            }

            //用户已关注的扫码事件
            if ($info['Event'] == 'SCAN') {
                //获取用户信息
                // Db::table('cx_test')->insertGetId(array('content'=>$info['FromUserName']));
                //关注成功，发送模板通知，通过二维码扫描关注
                $Notice = new Notice();
                if (!$this->isUserInfo($info['FromUserName'])) {
                    $Notice->pullUserInfo($info['FromUserName']);
                }
                $Notice->follow_notice($info['EventKey'], $info['FromUserName']);
            }
            //用户未关注的扫码事件
            echo 'success';


        }
    }


    /*
     *将XML转为array
    */
    private function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

    /**
     *
     * 判断数据库是否已经有次信息
     */

    private function isUserInfo($openid_web)
    {
        $User = new \app\api\model\User();
        $isID = $User->where('openid_web', $openid_web)->value('id');
        if ($isID) {
            $times = time();
            $User->where('id', $isID)->setField('is_subscribe_wechat', 1);
            $User->where('id', $isID)->setField('subscribe_time', $times);
            return true;
        }

        // 返回
        return false;
    }

    public function my_ebook()
    {
        $UserEbook = new \app\api\model\UserEbook();
        $infos = $UserEbook->where('uid',UID)->select();
        // $data = [];
        if($infos) {
            foreach ($infos as $key => $value) {
                $Ebook = \app\api\model\Ebook::where('id', $value['eid'])->find();
                $infos[$key]['ebook'] = [
                    'id'=>$Ebook['id'],
                    'title'=>$Ebook['title'],
                    'image'=>$Ebook['image'],
                ];
            }
        }
        if (!empty($infos)){
            json_success($infos);
        }
        json_success([]);
    }

    public function my_ebookcode()
    {
        $page=input('page',1);
        $limit=input('limit',15);
        $status['status']=['eq',1];

        $data['list']=Db('ebook_code')->field('id,code,is_use,eid')->where($status)->where(['uid'=>UID])->order('create_time desc')->page($page,$limit)->select();
        $data['count']=Db('ebook_code')->where(['uid'=>UID])->where($status)->count();
        if($data['list']) {
            foreach ($data['list'] as $key => $value) {
                $data['list'][$key]['ebook'] = [];
                $obj = Db('ebook')->where(['id'=>$value['eid']])->find();
                if($obj) {
                    $data['list'][$key]['ebook'] = [
                        'id'=>$obj['id'],
                        'title'=>$obj['title'],
                        'image'=>$obj['image'],
                    ];
                }
            }
        }
        if (!empty($data)){
            json_success($data);
        }
        json_success([]);
    }

    public function check_can_read()
    {
        $eid = input('eid');
        $map = [
            'uid'=>UID,
            'eid'=>$eid
        ];
        if(!(\app\api\model\UserEbook::where($map)->find())) {
            json_success("fail");
        } else {
            json_success("success");
        }
    }

    public function check_ebookcode()
    {
        $code = input('code');
        $eid = input('eid');
        $map = [
            // 'uid'=>UID,
            'code'=>$code,
            'eid'=>$eid,
            'is_use'=>0
        ];
        if(!($res = \app\api\model\EbookCode::where($map)->find())) {
            json_success('fail');
        } else {
            $data = [
                'uid'=>UID,
                'eid'=>$res['eid'],
                'status'=>1
            ];
            $UserEbook = new \app\api\model\UserEbook();
            $row = $UserEbook->allowField(true)->save($data);
            // 使用阅读码
            $ebookCodeObj = \app\api\model\EbookCode::where(["code"=>$code])->find();
            $ebookCodeObj->allowField(true)->save(['is_use'=>1]);
            json_success('success');
        }
    }

    public function add_ebookcode()
    {
        $num = input('num');
        $eid = input('eid');
        for ($i=0; $i < $num; $i++) { 
            $map = [
                'uid'=>UID,
                'code'=>$this->getRandomString(10),
                'eid'=>$eid,
                'status'=>1
            ];
            $EbookCode = new \app\api\model\EbookCode();
            $EbookCode->allowField(true)->save($map);
        }
    }

     public function getRandomString($len, $chars=null)  
    {  
        if (is_null($chars)) {  
            $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
        }  
        mt_srand(10000000*(double)microtime());  
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {  
            $str .= $chars[mt_rand(0, $lc)];  
        }  
        return $str;  
    } 

}